package com.example.demo.config;
//
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

//spring中配置RedisTemplate
@Configuration
public class RedisConfig {
    //聊天室订阅channnel 号
     public   static String CHAT_CHANNEL="chat_channel_999";
    //    redis-server.exe redis.windows.conf
//    作用是将数据结构转换为二进制格式，以便在Redis中存储和传输。
    /**
     * 配置redis序列化方式
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 使用String序列化Key
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());

        // 使用JSON序列化Value
        Jackson2JsonRedisSerializer<Object> serializer =
                new Jackson2JsonRedisSerializer<>(Object.class);
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);

        return template;
    }

    /*
    订阅redis

     */
    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory, MessageListener listener){
        RedisMessageListenerContainer container =new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅特定频道o
        //订阅聊天室频道
        container.addMessageListener(listener,new PatternTopic(CHAT_CHANNEL));
        return  container;
    }


    ///**
    // * 注册一个spring bean: redis消息处理
    // //* @param redisMessageSubscriberListener redis消息处理实例
    // */
    //@Bean
    //MessageListenerAdapter redisMessageListenerContainer(){
    //    return new MessageListenerAdapter(new RedisMessageSubscriberListener());
    //}


}